<template>
  <div class="checkout-page">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">確認訂單</h1>
        <div class="page-subtitle">請填寫收貨信息并確認訂單</div>
      </div>

      <div class="checkout-content">
        <!-- 收货信息 -->
        <div class="shipping-section">
          <h3 class="section-title">
            <el-icon class="title-icon"><Location /></el-icon>
            收貨信息
          </h3>
          <div class="shipping-form">
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">
                  收貨地址 <span class="required">*</span>
                </label>
                <el-cascader
                  v-model="shippingInfo.region"
                  :options="regionOptions"
                  placeholder="請選擇省/市/區"
                  class="region-selector"
                  :props="cascaderProps"
                  clearable
                  filterable
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group full-width">
                <label class="form-label">
                  詳細地址 <span class="required">*</span>
                </label>
                <el-input
                  v-model="shippingInfo.detailAddress"
                  placeholder="詳細地址、街道、門牌號等"
                  type="textarea"
                  :rows="3"
                  class="detail-address"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">
                  收貨人 <span class="required">*</span>
                </label>
                <el-input
                  v-model="shippingInfo.recipientName"
                  placeholder="請輸入收貨人姓名"
                  class="recipient-input"
                />
              </div>
              <div class="form-group">
                <label class="form-label">
                  手機號碼 <span class="required">*</span>
                </label>
                <el-input
                  v-model="shippingInfo.phone"
                  placeholder="請輸入手機號碼"
                  class="phone-input"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 订单產品 -->
        <div class="order-section">
          <h3 class="section-title">
            <el-icon class="title-icon"><ShoppingBag /></el-icon>
            訂單產品
          </h3>
          <div class="order-items">
            <div
              v-for="item in checkoutItems"
              :key="`${item.id}-${item.specs}`"
              class="order-item"
            >
              <div class="item-image-container">
                <img :src="item.image" :alt="item.name" class="item-image" />
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-specs" v-if="item.specs">{{ item.specs }}</div>
                <div class="item-sku" v-if="item.skuData">
                  <el-tag size="small" type="primary">{{ item.skuData.title }}</el-tag>
                </div>
                <div class="item-details">
                  <span class="item-price"><Currency/>{{ formatPrice(item.price) }}</span>
                  <span class="item-quantity">× {{ item.quantity }}</span>
                </div>
              </div>
              <div class="item-total">
                <span class="total-amount"><Currency/>{{ formatPrice(item.price * item.quantity) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单摘要 -->
        <div class="order-summary">
          <div class="summary-row">
            <span class="summary-label">產品總價</span>
            <span class="summary-value"><Currency/>{{ formatPrice(checkoutTotal) }}</span>
          </div>
          <div class="summary-row">
            <span class="summary-label">運費</span>
            <span class="summary-value free-shipping">免運費</span>
          </div>
          <div class="summary-divider"></div>
          <div class="summary-row total-row">
            <span class="summary-label">總計</span>
            <span class="summary-value total-price"><Currency/>{{ formatPrice(checkoutTotal) }}</span>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-section">
          <el-button
            type="primary"
            size="large"
            @click="submitOrder"
            :loading="submitting"
            class="submit-btn"
          >
            <el-icon class="btn-icon"><Check /></el-icon>
            確認訂單
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Location, ShoppingBag, Check } from '@element-plus/icons-vue'
import { formatPrice } from '@/utils/formatPrice.ts'
import regionData from '@/assets/region.json'
import {fetchSubmitOrder} from "@/request/req.ts";
import Currency from "@/components/common/Currency.vue";

// 地区数据类型
interface RegionData {
  [key: string]: {
    [key: string]: string
  }
}
const typedRegionData = regionData as RegionData
const router = useRouter()

// 响应式数据
const submitting = ref(false)
const checkoutItems = ref<any[]>([])
const checkoutTotal = ref(0)

// 收货信息
const shippingInfo = ref({
  region: [],
  detailAddress: '',
  recipientName: '',
  phone: ''
})

// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  emitPath: false
}

// 处理地区数据
const regionOptions = computed(() => {
  const provinces = typedRegionData['00'] // 获取省份数据
  const options: any[] = []

  Object.entries(provinces).forEach(([provinceCode, provinceName]) => {
    const provinceOption = {
      value: provinceCode,
      label: provinceName,
      children: [] as any[]
    }

    // 获取该省份下的城市数据
    const cities = typedRegionData[provinceCode]
    if (cities) {
      Object.entries(cities).forEach(([cityCode, cityName]) => {
        const cityOption = {
          value: cityCode,
          label: cityName,
          children: [] as any[]
        }

        // 获取该城市下的区县数据（如果有的话）
        const districts = typedRegionData[cityCode]
        if (districts && Object.keys(districts).length > 0) {
          Object.entries(districts).forEach(([districtCode, districtName]) => {
            cityOption.children.push({
              value: districtCode,
              label: districtName
            })
          })
        }

        provinceOption.children.push(cityOption)
      })
    }

    options.push(provinceOption)
  })

  return options
})

// 表单验证
const validateForm = () => {
  if (!shippingInfo.value.region || shippingInfo.value.region.length === 0) {
    ElMessage.error('請選擇收貨地址')
    return false
  }
  if (!shippingInfo.value.detailAddress.trim()) {
    ElMessage.error('請填寫詳細地址')
    return false
  }
  if (!shippingInfo.value.recipientName.trim()) {
    ElMessage.error('請填寫收貨人姓名')
    return false
  }
  if (!shippingInfo.value.phone.trim()) {
    ElMessage.error('請填寫手機號碼')
    return false
  }
  return true
}

// 提交订单
const submitOrder = async () => {
  if (!validateForm()) return

  submitting.value = true
  try {
    // 获取选中的地区名称
    const getRegionNames = () => {
      if (!shippingInfo.value.region || shippingInfo.value.region.length === 0) {
        return ''
      }

      // 如果region是数组，直接使用
      if (Array.isArray(shippingInfo.value.region)) {
        return shippingInfo.value.region.join(' ')
      }

      // 如果region是单个值，需要从regionOptions中找到对应的名称
      const findRegionName = (code: string, options: any[]): string => {
        for (const option of options) {
          if (option.value === code) {
            return option.label
          }
          if (option.children) {
            for (const child of option.children) {
              if (child.value === code) {
                return child.label
              }
              if (child.children) {
                for (const grandChild of child.children) {
                  if (grandChild.value === code) {
                    return grandChild.label
                  }
                }
              }
            }
          }
        }
        return ''
      }

      return findRegionName(shippingInfo.value.region, regionOptions.value)
    }

    // 构建数据
    const orderData = {
      Received: {
        address: getRegionNames() + ' ' + shippingInfo.value.detailAddress,
        recipient: shippingInfo.value.recipientName,
        phone: shippingInfo.value.phone
      },
      Order: checkoutItems.value.map((item: any) => {
        let originalId = item.id
        if (typeof item.id === 'string' && item.id.includes('_')) {
          originalId = item.id.split('_')[0]
        }

        return {
          Id: originalId,
          count: item.quantity,
          skuData: item.skuData || null,
        }
      })
    };

    // 将数据转换为字符串
    const orderDataString = JSON.stringify(orderData)

    const formData = new FormData()
    formData.append('o', orderDataString)

    // API提交订单
    const res = await fetchSubmitOrder(formData)

    // 检查API响应
    if (res && res.CartOrders) {
      ElMessage.success('訂單提交成功！')

      // 清空sessionStorage
      sessionStorage.removeItem('checkoutItems')
      sessionStorage.removeItem('checkoutTotal')

      // 跳转到订单页面，传递订单号
      await router.push({
        path: '/order',
        query: {
          keyword: res.CartOrders,
          type: 'DD'
        }
      })
    } else {
      ElMessage.error('訂單提交失败，请重试')
    }
  } catch (error) {
    ElMessage.error('訂單提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  // 从sessionStorage获取结算產品信息
  const items = sessionStorage.getItem('checkoutItems')
  const total = sessionStorage.getItem('checkoutTotal')

  if (items && total) {
    checkoutItems.value = JSON.parse(items)
    checkoutTotal.value = parseFloat(total)
  } else {
    // 如果没有结算信息，跳转回购物车
    ElMessage.warning('请先选择要购买的產品')
    router.push('/cart')
  }
})
</script>

<style scoped>
.checkout-page {
  background: var(--bg-tertiary);
  min-height: 100vh;
  padding: var(--spacing-xl) 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 var(--spacing-xl);
}

/* 页面标题 */
.page-header {
  background: var(--gradient-bg-primary);
  padding: var(--spacing-2xl);
  border-radius: var(--radius-xl);
  margin-bottom: var(--spacing-2xl);
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
}

.page-title {
  font-size: var(--font-size-3xl);
  font-weight: var(--font-weight-bold);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
}

.page-subtitle {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

/* 结算内容 */
.checkout-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-2xl);
}

/* 收货信息 */
.shipping-section,
.order-section {
  background: var(--gradient-bg-primary);
  border-radius: var(--radius-xl);
  padding: var(--spacing-2xl);
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
}

:deep(.el-cascader__dropdown) {
  background-color: var(--bg-secondary);
  border-color: var(--border-dark);
}

:deep(.el-cascader-node) {
  color: var(--text-primary);
}

:deep(.el-cascader-node:not(.is-disabled):hover),
:deep(.el-cascader-node:not(.is-disabled):focus) {
  background-color: var(--primary-bg);
}

:deep(.el-cascader-node.in-active-path),
:deep(.el-cascader-node.is-active),
:deep(.el-cascader-node.is-selectable.in-checked-path) {
  color: var(--primary-color);
  background-color: var(--primary-bg);
}

/* 修复输入框聚焦时的边框问题 */
:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  outline: none;
  box-shadow: none;
}

/* 修复级联选择器的样式 */
:deep(.el-cascader) {
  width: 100%;
  border: none;
}

:deep(.el-cascader .el-input .el-input__suffix) {
  right: 0;
}

:deep(.el-cascader .el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid var(--border-dark) !important;
}

/* 完全移除所有边框 */
:deep(.el-input),
:deep(.el-textarea),
:deep(.el-cascader) {
  --el-border-color: transparent;
  --el-border-color-hover: transparent;
  --el-border-color-focus: transparent;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__wrapper) {
  border: none !important;
  border-bottom: 1px solid var(--border-dark) !important;
}

.section-title {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin-bottom: var(--spacing-xl);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.title-icon {
  color: var(--primary-color);
}

.shipping-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

.form-row {
  display: flex;
  gap: var(--spacing-xl);
}

.form-group {
  flex: 1;
}

.form-group.full-width {
  flex: 1;
}

.form-group :deep(.el-input),
.form-group :deep(.el-textarea),
.form-group :deep(.el-cascader) {
  --el-fill-color-blank: var(--bg-secondary);
  --el-input-bg-color: var(--bg-secondary);
  --el-input-border-color: transparent;
  --el-input-hover-border-color: transparent;
  --el-input-focus-border-color: transparent;
  --el-input-text-color: var(--text-primary);
  --el-input-hover-border: none;
  --el-input-focus-border: none;
  --el-input-border-radius: 0;
  --el-border-color: transparent;
  --el-border-color-light: transparent;
  --el-border-color-extra-light: transparent;
  border: none;
}

.form-label {
  display: block;
  font-size: var(--font-size-sm);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  font-weight: var(--font-weight-medium);
}

.required {
  color: var(--primary-color);
}

/* 订单產品 */
.order-items {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.order-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-lg);
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-secondary);
}

.item-image-container {
  width: 80px;
  height: 80px;
  border-radius: var(--radius-lg);
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: var(--shadow-soft);
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  line-height: 1.4;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-specs {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  margin-bottom: var(--spacing-sm);
  background: var(--bg-primary);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-md);
  display: inline-block;
}

.item-sku {
  margin-bottom: var(--spacing-sm);
}

.item-sku .el-tag {
  background: var(--gradient-primary);
  border-color: var(--primary-color);
  color: var(--text-light);
}

.item-details {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.item-price {
  font-size: var(--font-size-sm);
  color: var(--primary-color);
  font-weight: var(--font-weight-semibold);
}

.item-quantity {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  background: var(--bg-primary);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
}

.item-total {
  text-align: right;
  min-width: 80px;
}

.total-amount {
  font-size: var(--font-size-lg);
  color: var(--primary-color);
  font-weight: var(--font-weight-bold);
}

/* 订单摘要 */
.order-summary {
  background: var(--gradient-bg-primary);
  border-radius: var(--radius-xl);
  padding: var(--spacing-2xl);
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-md);
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.summary-value {
  font-size: var(--font-size-sm);
  color: var(--text-primary);
  font-weight: var(--font-weight-medium);
}

.free-shipping {
  color: var(--success-color);
  font-weight: var(--font-weight-semibold);
}

.summary-divider {
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--border-secondary), transparent);
  margin: var(--spacing-lg) 0;
}

.total-row {
  margin-top: var(--spacing-lg);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--border-secondary);
}

.total-row .summary-label {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
}

.total-price {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-bold);
  color: var(--primary-color);
}

/* 提交按钮 */
.submit-section {
  display: flex;
  justify-content: center;
  padding: var(--spacing-2xl) 0;
}

.submit-btn {
  background: var(--gradient-primary);
  border: none;
  color: var(--text-light);
  padding: var(--spacing-lg) var(--spacing-4xl);
  border-radius: var(--radius-xl);
  font-weight: var(--font-weight-semibold);
  font-size: var(--font-size-base);
  box-shadow: var(--shadow-button);
  transition: var(--transition-all);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

/* 覆盖Element Plus按钮样式 */
:deep(.el-button--primary) {
  background: var(--gradient-primary);
  border-color: transparent;
  color: var(--text-light);
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus) {
  background: linear-gradient(135deg, var(--primary-hover), var(--primary-color));
  border-color: transparent;
  color: var(--text-light);
}

.submit-btn:hover {
  background: linear-gradient(135deg, var(--primary-hover), var(--primary-color));
  box-shadow: var(--shadow-medium);
  transform: translateY(-2px);
}

.btn-icon {
  font-size: var(--font-size-lg);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 var(--spacing-lg);
  }

  .form-row {
    flex-direction: column;
    gap: var(--spacing-lg);
  }

  .order-item {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }

  .item-image-container {
    width: 100%;
    height: 120px;
  }

  .item-total {
    text-align: left;
    width: 100%;
  }

  .submit-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>
